<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.propId ? $t('crud.addTitle') : $t('resource.update')"
    :close-on-click-modal="false"
    style="min-width: 700px;"
    top="50px"
  >
    <el-form
      ref="formRef"
      label-width="80px"
      :class="{'en-form':$t('language')==='English'}"
      class="page-spec"
      @submit.prevent
    >
      <el-form-item
        v-if="langItemList.length > 1"
        :label="$t('spec.selectLang')"
      >
        <el-select
          v-model="curLang"
          multiple
          :placeholder="$t('tip.select')"
          style="width: 450px;"
          @change="selectLang"
        >
          <el-option
            v-for="item in langItemList"
            :key="item.lang"
            :label="item.name"
            :value="item.lang"
          />
        </el-select>
        <p style="font-size:12px;color:#999999;line-height:20px;">
          {{ $t('spec.selectTips') }}
        </p>
      </el-form-item>

      <!-- 规格名称 -->
      <el-form-item :label="$t('spec.specName')">
        <div
          v-for="(item,inx) in prodPropLangList"
          :key="inx"
          class="attr-name"
        >
          <el-input
            v-model.trim="item.propName"
            :placeholder="$t('spec.specName') + (langItemList.length === 1 ? '' : `(${item.langName})`)"
            maxlength="10"

            show-word-limit
            clearable
            @blur="item.propName = handleInputSpaces(item.propName, 0)"
          />
        </div>
        <p style="font-size:12px;color:#999999;line-height:20px;">
          {{ $t('spec.specNameTips') }}
        </p>
      </el-form-item>

      <el-form-item :label="$t('spec.specValue')">
        <div
          class="default-btn primary-btn"
          @click="add"
        >
          {{ $t('prodSku.add') }}
        </div>
        <p style="font-size:12px;color:#999999;line-height:20px;">
          {{ $t('spec.specValueTips') }}
        </p>
      </el-form-item>

      <!-- 规格值 -->
      <el-form-item>
        <div
          v-for="(item,index) in prodPropValues"
          :key="index"
          class="attr-value-box"
        >
          <div class="left-box">
            <div
              v-for="(prop,propInx) in item.prodPropValueLangList"
              :key="propInx"
              class="attr-value"
            >
              <el-input
                v-model.trim="prop.propValue"

                maxlength="20"
                clearable
                :placeholder="$t('spec.specValue') + (langItemList.length === 1 ? '' : `(${prop.langName})`)"
                @blur="prop.propValue = handleInputSpaces(prop.propValue, 1)"
              />
            </div>
          </div>
          <div
            class="value-del-btn"
            @click="deleteRow(index)"
          >
            {{ $t('resource.Delete') }}
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("crud.filter.cancelBtn") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t("crud.filter.submitBtn") }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const visible = ref(false)
let isSubmit = false
const dataForm = ref({ // 表单数据
  propId: 0
})
const prodPropLangList = ref([])
const prodPropValues = ref([])
const init = (val) => {
  isSubmit = false
  if (val) {
    dataForm.value = JSON.parse(JSON.stringify(val))
    prodPropLangList.value = dataForm.value.prodPropLangList
    prodPropValues.value = dataForm.value.prodPropValues
  } else {
    prodPropLangList.value = []
    prodPropValues.value = [{
      propId: dataForm.value.propId,
      prodPropValueLangList: [],
      propValue: '',
      propValueEn: ''
    }]
  }
  // 获取国际化配置语言
  getLangList()
  visible.value = true
}

// 语言列表
const langItemList = ref([])
const masterLangInfo = reactive({ name: '', lang: '' })
const curLang = ref([]) // 当前所选语言
const getLangList = () => {
  http({
    url: http.adornUrl('/sys/lang'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      const info = data
      masterLangInfo.name = info.name
      masterLangInfo.lang = info.lang
      langItemList.value = info.langItemList

      // 设置默认主语言
      if (!prodPropLangList.value.length) {
        selectLang([info.lang])
      } else {
        const curLang = []
        // 初始化所选语言
        const temPprodPropLangList = []
        for (const item of langItemList.value) {
          const fd = prodPropLangList.value.find(it => it.lang === item.lang)
          if (fd) {
            fd.langName = item.name
            temPprodPropLangList.push(fd)
            curLang.push(item.lang)
          }
        }
        prodPropLangList.value = temPprodPropLangList
        // 初始化规格值
        for (const item of prodPropValues.value) {
          for (const prop of item.prodPropValueLangList) {
            const fd = langItemList.value.find(it => it.lang === prop.lang)
            if (fd) {
              prop.langName = fd.name
            }
          }
        }
        selectLang(curLang)
      }
    }
  })
}

/**
 * 输入框纯空格处理
 */
const handleInputSpaces = (value, type) => {
  if (!value) return
  value = specInputLimit(value, type)
  return value.trim()
}
/**
 * 输入特殊字符处理
 */
const specInputLimit = (value, type = 0) => {
  const reg = /[\\;\\:\\；\\：]/g
  const regVal = /[\\;\\；]/g
  const negativeNumStr = '-'

  if (type === 0) {
    if (reg.test(value)) {
      ElMessage.error($t('product.specName') + $t('product.specialWordSymbolTips') + ':;')
      return ''
    }
  } else {
    if (regVal.test(value)) {
      ElMessage.error($t('product.specValue') + $t('product.specialWordSymbolTips') + ';')
      return ''
    }
    if (value.search(negativeNumStr) !== -1) {
      ElMessage.error($t('product.specValue') + $t('product.specialWordSymbolTips') + '-')
      return ''
    }
  }

  return value
}

// 多选框默认选择中文
const selectLang = (value) => {
  curLang.value = value
  // 设置主语言不可删除
  if (!curLang.value.includes(masterLangInfo.lang)) {
    curLang.value.unshift(masterLangInfo.lang)
  }
  // 规格名
  const tempArr = prodPropLangList.value.filter(item => curLang.value.includes(item.lang))
  curLang.value.forEach((item, index) => {
    if (!tempArr.find(f => f.lang == item)) {
      const fd = langItemList.value.find(it => it.lang === item)
      if (fd) {
        tempArr.splice(index, 0, { langName: fd.name, lang: item, propId: dataForm.value.propId, propName: '' })
      }
    }
  })
  prodPropLangList.value = tempArr

  // 规格值
  prodPropValues.value.forEach(prop => {
    const flList = prop.prodPropValueLangList.filter(item => curLang.value.includes(item.lang))
    curLang.value.forEach((item, index) => {
      if (!flList.find(f => f.lang == item)) {
        const fd = langItemList.value.find(it => it.lang === item)
        if (fd) {
          flList.splice(index, 0, { langName: fd.name, lang: item, propValue: '' })
        }
      }
    })
    prop.prodPropValueLangList = flList
  })
}

// 表单提交
const onSubmit = () => {
  // 是否存在未填的规格
  for (const item of prodPropValues.value) {
    for (const propItem of item.prodPropValueLangList) {
      // propItem.propValue = propItem.propValue.trim()
      if (!propItem.propValue) {
        ElMessage.error($t('spec.specValueCannotEmpty'))
        return
      }
    }
  }

  // 判断是否有相同的属性值
  for (let i = 0; i < prodPropValues.value.length; i++) {
    for (let j = i + 1; j < prodPropValues.value.length; j++) {
      // 规格
      for (let k = 0; k < prodPropValues.value[i].prodPropValueLangList.length; k++) {
        if (prodPropValues.value[i].prodPropValueLangList[k].propValue === prodPropValues.value[j].prodPropValueLangList[k].propValue) {
          ElMessage.error($t('product.same'))
          return
        }
      }
    }
  }

  for (const item of prodPropLangList.value) {
    if (!item.propName) {
      ElMessage.error($t('product.attributeNameNoNull'))
      return
    }
  }
  if (isSubmit) {
    return false
  }
  isSubmit = true

  const params = {
    propId: dataForm.value.propId || 0,
    propName: prodPropLangList.value[0].propName,
    prodPropLangList: prodPropLangList.value,
    prodPropValues: prodPropValues.value
  }

  http({
    url: http.adornUrl('/prod/spec'),
    method: dataForm.value.propId ? 'put' : 'post',
    data: http.adornData(params)
  }).then(() => {
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
        visible.value = false
        emit('refreshDataList', page)
      }
    })
  }).catch(() => {
    isSubmit = false
  })
}
/**
 * 添加一行规格
 */
const add = () => {
  for (const item of prodPropValues.value) {
    for (const prop of item.prodPropValueLangList) {
      if (!prop.propValue) {
        ElMessage.error($t('spec.specValueCannotEmpty'))
        return
      }
    }
  }
  // 添加行
  const prodPropValueLangList = []
  curLang.value.forEach(item => {
    const fd = langItemList.value.find(it => it.lang === item)
    prodPropValueLangList.push({ langName: fd.name, lang: item, propValue: '' })
  })
  prodPropValues.value.unshift({
    propId: dataForm.value.propId,
    propValue: '',
    propValueEn: '',
    prodPropValueLangList
  })
}
/**
 * 删除一行规格
 */
const deleteRow = (index) => {
  if (prodPropValues.value.length <= 1) {
    ElMessage.error($t('spec.specValueCannotDel'))
    return
  }
  prodPropValues.value.splice(index, 1)
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
.page-spec{
  :deep(.el-form-item__content) {
    display: block;
  }
  .attr-name{
    width: 230px;
    display: inline-block;
    padding: 6px 12px;
    border: 1px solid #e8eef5;
  }

}

.attr-value-box{
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e8eef5;
  .left-box{
    max-width: 500px;
    .attr-value{
      width: 230px;
      display: inline-block;
      padding-right: 12px;
    }
  }
  .value-del-btn{
    color: #447cdd;
    cursor: pointer;
  }
}
.en-form :deep(.el-form-item__label){
 word-break: break-word;
}
</style>
